package com.dhy.controller;

import com.dhy.config.LoadBalancer;
import com.dhy.msg.CommonResult;
import com.dhy.pojo.Payment;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;
@RestController
@Slf4j
public class OrderController
{
    @Autowired
    private RestTemplate restTemplate;
    private static  final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE";
    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/payment/getForEntity/{id}")
    public CommonResult<Payment> getPayment2(@PathVariable("id") Long id)
    {
        //获取当前指定服务名对应的服务集群里面所有服务
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        //如果服务为空，或者没有服务可用，那么返回null
        if(instances == null || instances.size() <= 0){
            return null;
        }
        //获得根据轮询算法，得到当前需要提供服务的那个服务
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        //获取这个服务的请求路径
        URI uri = serviceInstance.getUri();
        System.out.println("当前服务的URI为:"+uri);
        //返回的请求体内容，封面为CommonResult对象
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(uri+"/payment/get/"+id,CommonResult.class);
        //判断状态码
        if(entity.getStatusCode().is2xxSuccessful()){
             log.info(entity.getStatusCode()+"   "+entity.getStatusCodeValue());
           //返回请求体里面的内容
            return entity.getBody();//getForObject()
        }else{
            return new CommonResult<>(444,"操作失败");
        }
    }

    // ====================> zipkin+sleuth
    @GetMapping("/consumer/payment/zipkin")
    public String paymentZipkin()
    {
        String result = restTemplate.getForObject("http://localhost:8001"+"/payment/zipkin/", String.class);
        return result;
    }

}
